/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import entities.Person;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

/**
 *
 * @author Оксана
 */
public class PersonDaoImpl extends AbstractDao implements PersonDao {

    @Autowired
    public PersonDaoImpl(JdbcTemplate jdbcTemplate) {
        super(jdbcTemplate);
    }
    
    @Override
    public void create(Person person) {
        jdbcTemplate.update("insert into persons (id, surname, name, birthday, "
                + "login, password, is_tutor) values (?,?,?,?,?,?,?)", 
                person.getId(), person.getSurname(), person.getName(), 
                person.getBirthday(), person.getLogin(), person.getPassword(),
                person.isTutor() ? 1 : 0);
    }

    @Override
    public Person findByLoginPassword(String login, String password) {
        return jdbcTemplate.queryForObject("select id, surname, name, birthday, "
                + "login, password, is_tutor from persons where login = ? and password = ?", 
                new Object[] {login, password}, new PersonMapper());
    }

    @Override
    public Person findById(Integer id) {
        return jdbcTemplate.queryForObject("select * from persons where id = ?", 
                new Object[] {id}, new PersonMapper());
    }
    
    private final static class PersonMapper implements RowMapper<Person>{

        @Override
        public Person mapRow(ResultSet rs, int i) throws SQLException {
            Person person = new Person();
            person.setId(rs.getInt("id"));
            person.setSurname(rs.getString("surname"));
            person.setName(rs.getString("name"));
            person.setBirthday(rs.getDate("birthday"));
            person.setLogin(rs.getString("login"));
            person.setPassword(rs.getString("password"));
            person.setTutor(rs.getInt("is_tutor") == 1);
            return person;
        }       
    }
}